home *** CD-ROM | disk | FTP | other *** search
- Path: news.compuserve.com!newsmaster
- From: 100754.2730@compuserve.com (Martin Aupperle)
- Newsgroups: comp.lang.c++
- Subject: Re: Q: Returning a reference
- Date: Fri, 26 Jan 1996 10:01:16 GMT
- Organization: CompuServe Incorporated
- Message-ID: <4ea94a$kq6@dub-news-svc-1.compuserve.com>
- References: <4cvsm2$5ig@dub-news-svc-4.compuserve.com> <30FA95E1.50C@public.sta.net.cn> <4dp1a7$bo8@phoenix.dse.beckman.com>
- NNTP-Posting-Host: ad02-055.compuserve.com
- X-Newsreader: Forte Free Agent v0.56
-
- jawalker@ccgate.dp.beckman.com (Jack Walker) wrote:
-
- >Xu Ji <jafd@public.sta.net.cn> wrote:
-
- >>Martin Aupperle wrote:
- >>:
- >>: Borland C++ V4.5 does not allow to return a reference to a local
- >>: variable:
- >>:
- >>: int &doIt() {
- >>:
- >>: int i = 7;
- >>: return i; // syntax error
- >>: }
- >>:
- >>: I remember that I once had a compiler that did allow it (it gave me
- >>: only a warning).
- >>: Which one is right? I think that it should be an error because after
- >>: the function has terminated, the reference has no data object it is
- >>: bound to any more.
- >>:
- >>: Martin
- >>:
- >>: -----------------------------------
- >>: Signatures are a waste of bandwidth
- >>: -----------------------------------
-
- >>I think it should be an error, and I test it under Borland C++
- >>and Watcom C++, both this two compiler report it as an error.
-
- >>but the following function can be compiled:
-
- >> int &doIt()
- >> {
- >> int i = 7;
- >> return (int &)i;
-
- You can do everything with typecasts. The compiler's type system is
- faked if you tell it explicitely that you have a type B at a storage
- location where you created an A in the first place. So if you
- EXPLICITELY type cast to int &, it will be syntactically ok, of
- course (but it will crash anyway, what sheds a light on typecasts,
- IMO).
-
- >> }
-
- >>Best wishs,
- >>Xu yifeng
-
- >Do you really want to return a reference to an object that is
- >allocated on the stack? After doIt returns the space that i occupied
- >is available to be overwritten when the next stack frame is created.
-
- No, of course not. But I want my compiler to flag such a thing as an
- error, if it happens occasionaly. Please note that if the function
- would have been declared
-
- int doit();
-
- everything would be alright. It is easy to overlook the one character
- difference.
-
- What does the Standard say about references with a longer lifetime
- than the referenced object?
-
- Martin
-
-
-
-
-
-
- -----------------------------------
- Signatures are a waste of bandwidth
- -----------------------------------
-
-